Meteor.publish('mindMaps', function() {
  const query = {
    archived: false,
  };
  if (!!Meteor.userId()) query.userId = Meteor.userId();
  const mindMaps = MindMaps.find(query, {
    sort: { sort: 1 },
  });
  return mindMaps;
});

Meteor.publish('archivedMindMaps', function() {
  const userId = this.userId;
  if (!Match.test(userId, String)) return [];

  return MindMaps.find(
    {
      archived: true,
      userId: userId,
    },
    {
      sort: { modifiedAt: -1 },
    },
  );
});

Meteor.methods({
  copyMindMap(mindMapId, properties) {
    check(mindMapId, String);
    check(properties, Object);

    const mindMap = MindMaps.findOne(mindMapId);
    if (mindMap) {
      for (const key in properties) {
        mindMap[key] = properties[key];
      }
      return mindMap.copy();
    }
    return null;
  },
  restoreMindMap(mindMapId) {
    check(mindMapId, String);

    MindMaps.direct.update(
      {
        _id: mindMapId,
      },
      {
        $set: {
          archived: false,
        },
      },
    );
  },
});
